package com.project.service.impl;

import com.project.common.Result;
import com.project.dto.AuthDTO;
import com.project.entity.UserDb;
import com.project.mapper.UserDbMapper;
import com.project.service.UserDbService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.project.utils.DBUtil;
import com.project.utils.JwtUtil;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author Ao
 * @since 2024-04-26
 */
@Service
public class UserDbServiceImpl extends ServiceImpl<UserDbMapper, UserDb> implements UserDbService {

    @Override
    public Result<?> genDbAuthToken(AuthDTO auth, String userId) {
        // 查询数据库配置
        UserDb userDb = getById(auth.getId());
        if (userDb == null) {
            return Result.error("数据库信息查询失败！");
        }

        // 生成 token
        HashMap<String , Object> map = new HashMap<>();
        map.put("password", userDb.getDbPassword());
        map.put("userName", userDb.getUserName());
        map.put("dbName", userDb.getDbUserName());
        String url = DBUtil.getUrl(userDb.getIp(), userDb.getPort(), userDb.getDbUserName());
        map.put("url", url);
        map.put("userId", userId);

        Long exp = getExp(auth.getTtl(), auth.getType());

        String token = JwtUtil.createJWT(map);
        return Result.success(token);
    }
    private Long getExp(Long ttl, String type) {
        switch (type) {
            case "m":
                return TimeUnit.MINUTES.toMinutes(ttl);
            case "h":
                return TimeUnit.HOURS.toMinutes(ttl);
            case "d":
                return TimeUnit.DAYS.toMinutes(ttl);
            default:
                return -1L;
        }
    }
}
